﻿/*
 *	Copyright (c) 2009 Queensland University of Technology. All rights reserved.
 *	The QUT Bioinformatics Collection is open source software released under the 
 *	Microsoft Public License (Ms-PL): http://www.microsoft.com/opensource/licenses.mspx.
 */
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using QUT.Bio.Util;
using QUT.Bio.SilverMap.ObjectModel;

namespace QUT.Bio.SilverMap {
	public partial class HistoryPanel : UserControl {
		private ViewModel model;
		private readonly ObservableCollection<SequenceSummary> items = new ObservableCollection<SequenceSummary>();

		public HistoryPanel () {
			InitializeComponent();
			querySequenceSelector.ItemsSource = items;
		}

		public void Initialise ( ViewModel model ) {
			this.model = model;
			Refresh();
			model.ReferenceSequenceUpdated += Refresh;
			model.DataCollectionLoaded += Refresh;
			model.DataCollectionModified += Refresh;
		}

		private void Refresh () {
			items.Clear();
				
			List<SequenceSummary> itemsToRemove = new List<SequenceSummary>();

			if ( model == null || model.DataProducer == null ) {
				items.Clear();
			}
			else {
				HashList<ILinearDomain> currentQueries = model.DataProducer.FeatureCollection.Focii;

				foreach ( SequenceSummary item in items ) {
					if ( !currentQueries.Contains( item.Sequence ) ) {
						itemsToRemove.Add( item );
					}
				}

				foreach ( SequenceSummary item in itemsToRemove ) {
					items.Remove( item );
				}

				foreach ( ILinearDomain item in currentQueries ) {
					try {
					SequenceSummary summary = model.SequenceSummary[item];
					if ( ! items.Contains( summary ) ) {
						items.InsertInOrder( summary );
					}
					}
					catch {}
					
				}
				
				if ( model.ReferenceSequence != null ) {
					querySequenceSelector.SelectedItem = model.SequenceSummary[model.ReferenceSequence];
				}
			}
		}

		private void querySequenceSelector_SelectionChanged ( object sender, SelectionChangedEventArgs e ) {
			SequenceSummary selectedItem = (SequenceSummary) querySequenceSelector.SelectedItem;

			if ( selectedItem != null && selectedItem != model.ReferenceSequence ) {
				model.ReferenceSequence = selectedItem.Sequence;
			}
		}
	}
}
